package com.yyfax.pay.common.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Objects;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 快钱异步回调解密工具类
 * 
 * @author xiemh
 * @date 2016-08-30 19:34:04
 * @since v1.0.0
 */
public class QuickPayEncodeCerUtil {
	private static Logger logger = LoggerFactory.getLogger(QuickPayEncodeCerUtil.class);

	/** 签名算法 */
	private static final String SIGN_ALGORITHMS = "SHA1WithRSA";
	/** 签名参数 */
	private static Signature signature;

//	/** 单例模式*/
//	private static QuickPayEncodeCerUtil quickPayEncodeCerUtil;

	
	/**
	 * 私有构造函数
	 * 构造函数
	 */
	private QuickPayEncodeCerUtil(String wgwcerPath) {
		instance(wgwcerPath);
	}

	/**
	 * 初始化签名参数
	 * 
	 * @author xiemh
	 * @date 2016-09-28 15:46:35
	 * @since v1.0.0
	 */
	private static void instance(String wgwcerPath) {
		try {
			try (InputStream inStream = new FileInputStream(wgwcerPath)) {
				CertificateFactory cf = CertificateFactory.getInstance("X.509");
				X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
				PublicKey pk = cert.getPublicKey();
				signature = Signature.getInstance(SIGN_ALGORITHMS);
				signature.initVerify(pk);
			}
		} catch (Exception e) {
			logger.error("快钱初始化签名认证异常", e);
		}
	}

	/**
	 * RSA签名检查
	 * 
	 * @author xiemh
	 * @date 2016-09-01 09:56:00
	 * @since v1.0.0
	 * @param msg 待签名数据
	 * @param sign 签名值
	 * @return
	 * @throws SignatureException
	 * @throws Exception
	 */
	public static boolean enCodeByCer(String wgwcerPath, String content, String sign) throws SignatureException {
		if (Objects.equals(null, signature)) {
			instance(wgwcerPath);
		}
		signature.update(content.getBytes(Charset.forName("UTF-8")));
		return signature.verify(Base64.decodeBase64(sign));

	}
}
